//
//  JXMessage.m
//  JiaoX
//
//  Created by yinqy on 15/3/13.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXMessage.h"
#import "MD5Util.h"
@implementation JXMessage


+ (JXMessage *)messageForPeerWithSession:(AVSession *)session
                                toPeerId:(NSString *)toPeerId
                                 payload:(NSString *)payload{
    AVMessage *message = [[AVMessage messageForPeerWithSession:session toPeerId:toPeerId payload:payload] copy];
    
    JXMessage *jxmsg = [[JXMessage alloc]init];
    jxmsg.type = message.type;
    
    jxmsg.fromPeerId = message.fromPeerId;
    jxmsg.toPeerId = message.toPeerId;
    jxmsg.groupId = message.groupId;
    jxmsg.timestamp = [[Utils getCurrentTime] longLongValue];
    jxmsg.receiptTimestamp = message.receiptTimestamp;
    jxmsg.offline = message.offline;
    
    
    [jxmsg setMessageId:[NSString randomStringWithLength:24]];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:jxmsg.messageId forKey:@"objectId"];
    [dict setObject:[NSNumber numberWithInt:MsgTypeText] forKey:@"type"];
    [dict setObject:message.payload forKey:@"content"];
    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSString *playload = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    
    jxmsg.payload = playload;
    
    [jxmsg setRoomType:RoomTypeSingle];
    [jxmsg setMsgType:MsgTypeText];
    [jxmsg setReadStatus:ReadStatusHaveRead];
    return jxmsg;
}

+ (JXMessage *)imgMsgWithSession:(AVSession *)session objectId:(NSString *)objectId imgFile:(NSString *)imgFile toPeerId:(NSString *)toPeerId imgW:(CGFloat)imgW imgH:(CGFloat)imgH{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:objectId forKey:@"objectId"];
    [dict setObject:[NSNumber numberWithInt:MsgTypeImage] forKey:@"type"];
    [dict setObject:imgFile forKey:@"content"];
    [dict setObject:[NSNumber numberWithDouble:imgW] forKey:@"imgW"];
    [dict setObject:[NSNumber numberWithDouble:imgH] forKey:@"imgH"];
    
    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSString *playload = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    AVMessage *message = [AVMessage messageForPeerWithSession:session toPeerId:toPeerId payload:playload];
    
    JXMessage *jxmsg = [[JXMessage alloc]init];
    jxmsg.type = message.type;
    
    jxmsg.fromPeerId = message.fromPeerId;
    jxmsg.toPeerId = message.toPeerId;
    jxmsg.groupId = message.groupId;
    jxmsg.timestamp = [[Utils getCurrentTime] longLongValue];
    jxmsg.receiptTimestamp = message.receiptTimestamp;
    jxmsg.offline = message.offline;
    
    jxmsg.payload = playload;
    
    [jxmsg setMessageId:objectId];
    [jxmsg setRoomType:RoomTypeSingle];
    [jxmsg setMsgType:MsgTypeImage];
    [jxmsg setReadStatus:ReadStatusHaveRead];
    return jxmsg;
}

/**
 *  用于把收到的信息转成jxmessage;
 *
 *  @param message avmessage
 *
 *  @return
 */
+(JXMessage *)fromAVMessage:(AVMessage *)message{
    JXMessage * jxmsg = [[JXMessage alloc]init];
    
    jxmsg.type = message.type;
    jxmsg.fromPeerId = message.fromPeerId;
    jxmsg.toPeerId = message.toPeerId;
    jxmsg.groupId = message.groupId;
    jxmsg.timestamp = message.timestamp;
    jxmsg.receiptTimestamp = message.receiptTimestamp;
    jxmsg.offline = message.offline;
    jxmsg.payload = message.payload;
    
    NSData *jsonData = [message.payload dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *params = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    //消息的唯一id
    [jxmsg setMessageId:[params valueForKey:@"objectId"]];
    NSNumber *number = [params valueForKey:@"type"];
    [jxmsg setMsgType:[number intValue]];
    [jxmsg setReadStatus:ReadStatusUnread];
    if ([Utils isBlankString:message.groupId]) {
        [jxmsg setRoomType:RoomTypeSingle];
    }else{
        [jxmsg setRoomType:RoomTypeGroup];
    }
    return jxmsg;
}

+ (JXMessage *)fromFMResultSet:(FMResultSet *)set{
    JXMessage * jxmsg = [[JXMessage alloc]init];
    jxmsg.fromPeerId = [set stringForColumn:@"fromPeerId"];
    jxmsg.toPeerId = [set stringForColumn:@"toPeerId"];
    jxmsg.groupId = [set stringForColumn:@"groupId"];
    jxmsg.timestamp = [set longLongIntForColumn:@"timestamp"];
    jxmsg.messageId = [set stringForColumn:@"messageId"];
    jxmsg.payload = [set stringForColumn:@"content"];
    jxmsg.msgType = [set intForColumn:@"msgType"];
    if ([Utils isBlankString:jxmsg.groupId]) {
        [jxmsg setRoomType:RoomTypeSingle];
    }else{
        [jxmsg setRoomType:RoomTypeGroup];
    }
    jxmsg.readStatus = ReadStatusHaveRead;
    
    return jxmsg;
}

-(NSString *)actualContent{
    NSData *jsonData = [self.payload dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *params = [NSJSONSerialization JSONObjectWithData:jsonData
                                                           options:NSJSONReadingMutableContainers
                                                             error:&err];
    return [params valueForKey:@"content"];
}

-(void)setActualContent:(NSString *)actual{
    NSData *jsonData = [self.payload dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                           options:NSJSONReadingMutableContainers
                                                             error:nil];
    [dict setValue:actual forKey:@"content"];
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
    NSString *playload = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [self setPayload:playload];
}


-(CGFloat)getImgW{
    NSData *jsonData = [self.payload dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *params = [NSJSONSerialization JSONObjectWithData:jsonData
                                                           options:NSJSONReadingMutableContainers
                                                             error:nil];
    return [[params valueForKey:@"imgW"] floatValue];

}
-(CGFloat)getImgH{
    NSData *jsonData = [self.payload dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *params = [NSJSONSerialization JSONObjectWithData:jsonData
                                                           options:NSJSONReadingMutableContainers
                                                             error:nil];
    return [[params valueForKey:@"imgH"] floatValue];
}

-(NSString *)conversionId{
    if ([Utils isBlankString:self.toPeerId]) {
        //代表是群
    }else{
        NSArray *sortedKeys = [NSArray arrayWithObjects:self.toPeerId,self.fromPeerId, nil];
        NSArray *resultArray = [sortedKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            return [[NSString stringWithFormat:@"%@",obj1] compare:[NSString stringWithFormat:@"%@",obj2] options:NSNumericSearch];
        }];
        return [self shortAndMd5:resultArray];
    }
    return @"";
}

-(NSString *)shortAndMd5:(NSArray *)array{
    NSString *result = @"";
    for (NSString *key in array) {
        result = [result stringByAppendingFormat:@"%@",key];
    }
    return [MD5Util md5:result];
}

@end
